package org.example.slave.connector;

import lombok.Data;
import org.example.slave.channel.MyChannel;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author dingrui
 * @since 2022/2/16
 * @description
 */
@Data
public abstract class AbstractConnector implements Connector {

    protected MyChannel myChannel;

    // 连接状态(true=已连接 false=未连接)
    protected AtomicBoolean connectedStatus = new AtomicBoolean(false);

    @Override
    public void connect() {
        if (this.doConnect()) this.connectedStatus.set(true);
    }

    protected abstract boolean doConnect();

    @Override
    public void disConnect() {
        if (!this.connectedStatus.compareAndSet(true, false)) return;
        if (Objects.nonNull(this.myChannel)) this.myChannel.close();
    }

    @Override
    public void reConnect() {
        this.doConnect();
        this.connect();
    }

    @Override
    public boolean isConnected() {
        return Objects.nonNull(this.myChannel) && this.myChannel.isConnected();
    }
}
